package com.project.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.server.common.exception.BusinessException;
import com.project.server.entity.HealthRecord;
import com.project.server.entity.PatientInfo;
import com.project.server.entity.SysUser;
import com.project.server.mapper.HealthRecordMapper;
import com.project.server.mapper.PatientInfoMapper;
import com.project.server.mapper.SysUserMapper;
import com.project.server.service.DoctorPatientService;
import com.project.server.vo.PatientVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DoctorPatientServiceImpl implements DoctorPatientService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private HealthRecordMapper healthRecordMapper;


    @Autowired
    private PatientInfoMapper patientInfoMapper;

    @Override
    public Page<SysUser> getPatients(Long doctorId, Integer current, Integer size, String name) {
        Page<SysUser> page = new Page<>(current, size);

        // 先查询绑定了该医生的患者信息
        LambdaQueryWrapper<PatientInfo> patientWrapper = new LambdaQueryWrapper<>();
        patientWrapper.eq(PatientInfo::getDoctorId, doctorId);
        List<PatientInfo> patients = patientInfoMapper.selectList(patientWrapper);

        // 获取患者用户ID列表
        List<Long> userIds = patients.stream()
                .map(PatientInfo::getUserId)
                .collect(Collectors.toList());

        if (userIds.isEmpty()) {
            return new Page<>();
        }

        // 查询用户信息
        LambdaQueryWrapper<SysUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.in(SysUser::getId, userIds)
                .eq(SysUser::getRoleId, 3)
                .like(StringUtils.hasText(name),SysUser::getRealName,name);

        return sysUserMapper.selectPage(page, userWrapper);
    }

    @Override
    public PatientVO getPatientDetail(Long userId) {
        // 验证用户是否存在且是患者
        SysUser user = sysUserMapper.selectById(userId);
        if (user == null || !user.getRoleId().equals(3)) {
            throw new BusinessException("患者不存在");
        }

        // 查询患者详细信息
        PatientInfo patientInfo = patientInfoMapper.selectByUserId(userId);
        if (patientInfo == null) {
            throw new BusinessException("患者信息不存在");
        }

        // 组装VO对象
        PatientVO vo = new PatientVO();

        // 复制用户基本信息
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setPhone(user.getPhone());
        vo.setRealName(user.getRealName());
        vo.setAvatar(user.getAvatar());
        vo.setRoleId(user.getRoleId());
        vo.setStatus(user.getStatus());

        // 复制患者详细信息
        vo.setDoctorId(patientInfo.getDoctorId());
        vo.setAge(user.getAge());
        vo.setIdCard(patientInfo.getIdCard());
        vo.setGender(user.getGender());
        vo.setAddress(patientInfo.getAddress());
        vo.setMedicalHistory(patientInfo.getMedicalHistory());
        vo.setAllergies(patientInfo.getAllergies());
        vo.setFamilyHistory(patientInfo.getFamilyHistory());
        vo.setCreateTime(patientInfo.getCreateTime());
        vo.setUpdateTime(patientInfo.getUpdateTime());

        return vo;
    }

    @Override
    public Page<HealthRecord> getPatientRecords(Long userId, Integer current, Integer size) {
        // 验证患者是否存在
        SysUser user = sysUserMapper.selectById(userId);
        if (user == null || !user.getRoleId().equals(3)) {
            throw new BusinessException("患者不存在");
        }

        Page<HealthRecord> page = new Page<>(current, size);

        LambdaQueryWrapper<HealthRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HealthRecord::getUserId, userId)
               .orderByDesc(HealthRecord::getMeasureTime);
        Page<HealthRecord> healthRecordPage = healthRecordMapper.selectPage(page, wrapper);

//        记录类型：1-血压 2-血糖 3-体重 4-体温
/*
 <div>血压: {{ record.bloodPressure }}</div>
                <div>血糖: {{ record.bloodSugar }}</div>
                <div>体温: {{ record.temperature }}°C</div>
                <div>心率: {{ record.heartRate }}</div>
 */
        // 根据日期分类



        return healthRecordPage;
    }

    @Override
    @Transactional
    public void update(Long doctorId, Long userId,PatientInfo patientModel) {
        // 验证用户是否为患者
        SysUser user = sysUserMapper.selectById(userId);
        if (user == null || !user.getRoleId().equals(3)) {
            throw new BusinessException("用户不存在或不是患者");
        }

        // 更新患者信息
        PatientInfo patientInfo = patientInfoMapper.selectByUserId(userId);
        if (patientInfo == null) {
            patientInfo.setUserId(userId);
            patientInfo.setDoctorId(doctorId);
            patientInfoMapper.insert(patientInfo);
        } else {
            if (patientModel.getMedicalHistory() != null) {
                patientInfo.setMedicalHistory(patientModel.getMedicalHistory());
            }
            if (patientModel.getAddress() != null) {
                patientInfo.setAddress(patientModel.getAddress());
            }
            if (patientModel.getAllergies() != null) {
                patientInfo.setAllergies(patientModel.getAllergies());
            }
            if (patientModel.getFamilyHistory() != null) {
                patientInfo.setFamilyHistory(patientModel.getFamilyHistory());
            }
            patientInfo.setDoctorId(doctorId);
            patientInfoMapper.updateById(patientInfo);
        }
    }

    @Override
    @Transactional
    public void unbindPatient(Long doctorId, Long userId) {
        PatientInfo patientInfo = patientInfoMapper.selectByUserId(userId);
        if (patientInfo != null && patientInfo.getDoctorId().equals(doctorId)) {
            patientInfo.setDoctorId(null);
            patientInfoMapper.updateById(patientInfo);
        }
    }
}
